# 检测摄像头
import threading
import time
from queue import Queue

from py.uitls import PyUtil
from py.uitls.capture import Device

PyUtil.init_status = False


# 请在主线程中执行此方法
def init():
    # 注意，必须在主线程中初始化，否则报错 vidcap.Error: Creation of the filter graph failed.
    if not PyUtil.init_status:
        PyUtil.init_status = True
        PyUtil.q_stop = Queue()
        cam0 = Device(0)
        PyUtil.cams = [cam0]
        # 启动一个线程接收摄像头退出消息
        threading.Thread(target=handle_stop).start()


def handle_stop():
    while True:
        try:
            # 必须休眠，否则占用大量cpu
            time.sleep(1)
            if not PyUtil.q_stop.empty():
                pop = PyUtil.cams.pop()
                PyUtil.cams.append(Device(0))

                get = PyUtil.q_stop.get()
                if get == "stop":
                    if pop is not None:
                        pass
                    # pop.quit()
        except Exception as e:
            pass


def get_pic(pic_name):
    image = PyUtil.cams[0].get_image(2)
    PyUtil.q_stop.put("stop")
    # 然后再保存文件
    image.save(pic_name)
    return pic_name


def test():
    get_pic("aaa.jpg")
    get_pic("22aaa.jpg")

if __name__ == '__main__':
    init()
    threading.Thread(target=test).start()
